package com.yz.xyt.service.impl;

import com.yz.xyt.constant.Constants;
import com.yz.xyt.domain.LoginUser;
import com.yz.xyt.domain.User;
import com.yz.xyt.mapper.MenuMapper;
import com.yz.xyt.mapper.RoleMapper;
import com.yz.xyt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 用户详情处理类
 * spring security 调用
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //查询用户信息
        User user = userMapper.findByUserName(s);
        if (Objects.isNull(user)){
            throw new BadCredentialsException("用户名或密码错误");
        }
        if(user.getStatus().equals(Constants.ACCOUNT_DISABLE)){
            throw new AccountExpiredException("此账号已停用");
        }

        //查询用户权限
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        //查询用户角色
        List<String> roleList = roleMapper.selectUserRoles(user.getId());

        return new LoginUser(user,list,roleList);
    }
}
